// 引入token的方法
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserProfile, getUserDetailById } from '@/api/user'
//  重置路由的方法
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}

}

const mutations = {
  // 设置token
  setTokenMutations(state, val) {
    state.token = val

    // 设置 cookies token
    setToken(val)
  },
  // 移除token
  removeTokenMutations(state) {
    state.token = ''
    // 移除 cookies token
    removeToken()
  },
  // 设置用户信息
  setUserInfoMutations(state, val) {
    state.userInfo = val
  },
  // 删除用户信息
  removeUserInfoMutations(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录是异步的，不需添加 async  await
  async userLoginActions(context, data) {
    console.log(context)
    const res = await login(data)
    context.commit('setTokenMutations', res.data)
  },
  // 用户信息
  async userInfoActions(context) {
    const res = await getUserProfile()
    const userInfo = await getUserDetailById(res.data.userId)
    context.commit('setUserInfoMutations', { ...userInfo.data, ...res.data })
  },
  // 退出登录
  logOutActions(context) {
    // 清除token
    context.commit('removeTokenMutations')
    // 清除用户信息
    context.commit('removeUserInfoMutations')
    // 退出时重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

